package com.xyq.fs.util;

import java.io.BufferedInputStream;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

public class FileCodingUtil2 {

	/***
	 * 这是获取文本编码方式的代码
	 */
	private static CodepageDetectorProxy detector;

	static {
		detector = CodepageDetectorProxy.getInstance();
		detector.add(new ParsingDetector(false));
		detector.add(UnicodeDetector.getInstance());
		detector.add(JChardetFacade.getInstance());//
		// 需要第三方JAR包:antlr.jar、chardet.jar.
		detector.add(ASCIIDetector.getInstance());
	}

	static Map<String, String> map = new HashMap<>();

	static {
		map.put("Unicode", "Unicode");
		map.put("GBK", "GBK");
		map.put("US-ASCII", "US-ASCII");
		map.put("windows1252", "GBK");
		map.put("UTF-16LE", "UTF-16LE");
		map.put("UTF-16BE", "UTF-16BE");
		map.put("UTF-8", "UTF-8");
		map.put("UTF-16", "UTF-16");
		map.put("ISO-8859-1", "ISO-8859-1");
		map.put("GB18030", "GB18030");
	}

	public static String getCharsetName(Path path, int byteNum) throws IOException {

		if (Files.size(path) == 2)
			return "GBK";
		String charsetSstr = null;
		Charset charset = null;
		try (FileInputStream fis = new FileInputStream(path.toFile());
				BufferedInputStream bis = new BufferedInputStream(fis);) {
			charset = detector.detectCodepage(bis, 1024);
			charsetSstr = charset.name();
			if (map.get(charsetSstr) != null)
				return map.get(charsetSstr);

		} finally {
			charset = null;
			charsetSstr = null;
			path = null;

		}
		return "GBK";
	}

	public static void main(String[] args) throws IOException {

		Path path = Paths.get("f:\\2.txt");
		System.out.println(path.toFile().length());
		String sb = getCharsetName(path, 1024);
		System.out.println(sb);

	}
}
